import { useState, useEffect } from 'react';
import defaultAvatar from '../assets/avatar.png'; // 替换为你的默认头像路径
import { updateUserProfileService } from '../api/UserApi';

function AvatarSection({ url, userId, onAvatarUpdate }) {
  const [avatar, setAvatar] = useState(defaultAvatar); // 当前头像
  const [preview, setPreview] = useState(null); // 上传后预览
  const [isUploading, setIsUploading] = useState(false);
  const [error, setError] = useState('');

  useEffect(() => {
    console.log("Avatar URL received:", url);
    // 如果有传入的头像URL，则使用它
    if (url && url !== 'undefined' && url !== 'null') {
      console.log("Setting avatar to:", url);
      setAvatar(url);
    } else {
      console.log("No valid avatar URL provided, using default");
      setAvatar(defaultAvatar);
    }
  }, [url]);

  const handleUpload = async (e) => {
    const file = e.target.files[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      setError('请选择图片文件');
      return;
    }

    // 验证文件大小（限制为 2MB）
    if (file.size > 2 * 1024 * 1024) {
      setError('图片大小不能超过 2MB');
      return;
    }
    setError('');
    const url = URL.createObjectURL(file);
    setPreview(url);

    try {
      setIsUploading(true);
      const formData = new FormData();
      formData.append('id', userId);
      formData.append('avatarFile', file);

      console.log("Uploading avatar for user:", userId);
      console.log("FormData contents:", {
        id: userId,
        file: file.name,
        fileType: file.type,
        fileSize: file.size
      });

      const response = await updateUserProfileService(formData);
      console.log("Upload response:", response);

      if (response.success) {
        console.log("Upload successful, new avatar URL:", response.data.avatarUrl);
        const newAvatarUrl = response.data.avatarUrl;
        if (newAvatarUrl && newAvatarUrl !== 'undefined' && newAvatarUrl !== 'null') {
          setAvatar(newAvatarUrl);
          if (onAvatarUpdate) {
            onAvatarUpdate(newAvatarUrl);
          }
        } else {
          console.error("Invalid avatar URL received from server:", newAvatarUrl);
          setError('服务器返回的头像URL无效');
        }
        setPreview(null);
      } else {
        console.error("Upload failed:", response.message);
        setError(response.message || '上传失败');
      }
    } catch (err) {
      console.error("Upload error:", err);
      console.error("Error details:", {
        message: err.message,
        response: err.response?.data,
        status: err.response?.status
      });
      setError(err.response?.data?.message || '上传失败，请重试');
    } finally {
      setIsUploading(false);
    }
  };

  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '40px' }}>
      {/* 当前头像 */}
      <div style={{ width: '48%' }}>
        <h3 style={{ borderBottom: '1px solid #ccc', paddingBottom: '8px' }}>当前头像</h3>
        <div style={{ marginTop: '20px' }}>
          <img
            src={avatar}
            alt="当前头像"
            style={{
              width: '120px',
              height: '120px',
              borderRadius: '8px',
              boxShadow: '0 2px 8px rgba(0,0,0,0.1)',
              objectFit: 'cover',
            }}
            onError={(e) => {
              console.error("Avatar image failed to load:", avatar);
              e.target.src = defaultAvatar;
            }}
          />
        </div>
      </div>

      {/* 设置新头像 */}
      <div style={{ width: '48%' }}>
        <h3 style={{ borderBottom: '1px solid #ccc', paddingBottom: '8px' }}>设置新头像</h3>
        <div style={{ marginTop: '20px' }}>
          <input
            type="file"
            accept="image/*"
            onChange={handleUpload}
            style={{ marginBottom: '10px' }}
            disabled={isUploading}
          />
          {error && (
            <div style={{ color: '#ff4d4f', marginBottom: '10px' }}>
              {error}
            </div>
          )}
          {isUploading && (
            <div style={{ marginBottom: '10px' }}>
              <span className="btn-spinner"></span>
              上传中...
            </div>
          )}
          {preview && (
            <div>
              <p style={{ marginBottom: '5px' }}>预览：</p>
              <img
                src={preview}
                alt="预览头像"
                style={{
                  width: '100px',
                  height: '100px',
                  borderRadius: '8px',
                  objectFit: 'cover',
                  border: '1px solid #ddd'
                }}
              />
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

export default AvatarSection;